package 笔试.网易;

public class Demo4 {
        /**
         * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
         * <p>
         * 计算最小航行费用
         *
         * @param input int整型二维数组 二维网格
         * @return int整型
         */
        public int minSailCost(int[][] input) {
            // write code here
            if (input.length == 0) return 0;
            int m = input.length, n = input[0].length;
            int[][] dp = new int[m][n];
            dp[0][0] = 0;
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (i == 0 && j == 0) continue;

                    if (input[i][j] == 2) dp[i][j] = -1;
                    else {
                        if (i == 0) {
                            if (dp[i][j - 1] == -1) {
                                dp[i][j] = -1;
                            }else {
                                dp[i][j] = dp[i][j-1] + (input[i][j] == 0 ? 2: 1);
                            }
                        }else if (j == 0) {
                            if (dp[i - 1][j] == -1) {
                                dp[i][j] = -1;
                            } else {
                                dp[i][j] = dp[i - 1][j] + (input[i][j] == 0 ? 2: 1);
                            }
                        }else {
                            if(dp[i][j-1] == -1 && dp[i-1][j] == -1) {
                                dp[i][j] = -1;
                            }else if(dp[i][j-1] == -1) {
                                dp[i][j] = dp[i-1][j] + (input[i][j] == 0 ? 2: 1);
                            }else if(dp[i - 1][j] == -1) {
                                dp[i][j] = dp[i][j - 1] + (input[i][j] == 0 ? 2: 1);
                            }else {
                                dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1]) +  (input[i][j] == 0 ? 2: 1);
                            }
                        }
                    }
                }
            }
            return dp[m - 1][n - 1];
        }

        public static void main(String[] args) {
            int [][]arr = {
                    {1,1,1,1,0},{0,1,0,1,0},{1,1,2,1,1},{0,2,0,0,1}
            };
            System.out.println(new Demo4().minSailCost(arr));
        }

}
